package com.bluesmart.mia;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sys.DemoApp;
import com.util.Constant;
import com.util.MgqDataHandler;
import com.util.MgqRestClient;
import com.util.PreferencesUtils;
import com.util.Utils;
import com.widget.HorizontalListView;
import com.widget.VerticalProgressBar;
import com.widget.MilkWave;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.RelativeLayout;
import android.widget.TextView;

@SuppressLint("NewApi")
public class DashboardActivity extends RelativeLayout implements
		OnClickListener, OnTouchListener {
	Context mContext;
	JSONArray mArray = new JSONArray();
	HorizontalListViewAdapter mAdapter;

	JSONObject mChartData[] = new JSONObject[7];
	int mSelected = -1;
	int mHeight = 0;
	int mScreenWidth;
	int totalGoal;

	// boolean showRotato = false;

	public DashboardActivity(Context context, AttributeSet attrs) {
		super(context, attrs);
		mContext = context;
		initView();
	}

	public DashboardActivity(Context context, AttributeSet attrs, int arg0) {
		super(context, attrs);
		mContext = context;
		initView();
	}

	public void initView() {
		LayoutInflater mInflater = LayoutInflater.from(mContext);
		addView(mInflater.inflate(R.layout.activity_dashboard, null));

		final HorizontalListView hlv = (HorizontalListView) findViewById(R.id.hl);
		mAdapter = new HorizontalListViewAdapter(mContext);
		hlv.setAdapter(mAdapter);
		hlv.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				mSelected = arg2;
				mAdapter.notifyDataSetChanged();
				((ViewPager) findViewById(R.id.vp)).setCurrentItem(mSelected,true);
				setProgeress(arg2);
			}
		});

		findViewById(R.id.note).setOnClickListener(this);
		findViewById(R.id.vp).setOnTouchListener(this);

		((MilkWave) findViewById(R.id.wave_view)).setProgress(0, "", "");

		sendHttpRequest(true);
	}

	@Override
	public boolean onTouch(View arg0, MotionEvent arg1) {
		if (arg1.getAction() == MotionEvent.ACTION_DOWN) {
			pointX = arg1.getX();
			pointY = arg1.getY();
		} else if (arg1.getAction() == MotionEvent.ACTION_UP) {
			if(arg0.getId() == R.id.vp)
			{
				if (arg1.getY() - pointY > 160) {
					((MainPageActivity) mContext).changeView(R.id.btn2);
				}
			}
			else
			{
				if (Math.abs(arg1.getX() - pointX) > Math.abs(arg1.getY() - pointY)) {
					if (arg1.getX() - pointX < -160) {
						changeTime(false);
						((ViewPager) findViewById(R.id.vp)).setCurrentItem(mSelected,true);
						return true;
					} else if (arg1.getX() - pointX > 160) {
						changeTime(true);
						((ViewPager) findViewById(R.id.vp)).setCurrentItem(mSelected,true);
						return true;
					}
				} else if (arg1.getY() - pointY > 160) {
					((MainPageActivity) mContext).changeView(R.id.btn2);
					return true;
				}
			}
		}

		if(arg0.getId() == R.id.vp) return arg0.onTouchEvent(arg1);
		return true;
	}

	float pointX = 0;
	float pointY = 0;

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		/*
		 * case R.id.share: ShareActivity.mScreenShot =
		 * convertViewToBitmap(findViewById(R.id.screen));
		 * mContext.startActivity(new Intent(mContext,ShareActivity.class));
		 * break;
		 */

		case R.id.note:
			mContext.startActivity(new Intent(mContext, BabyMilkActivity.class));
			break;
		/*
		 * case R.id.week0: case R.id.week1: case R.id.week2: case R.id.week3:
		 * case R.id.week4: case R.id.week5: case R.id.week6:
		 * ((MainPageActivity)mContext).intoWeek(R.id.btn1,arg0.getId() -
		 * R.id.week0 + 1); break;
		 */
		}
	}

	public Bitmap convertViewToBitmap(View view) {
		WindowManager wm = (WindowManager) mContext
				.getSystemService(Context.WINDOW_SERVICE);
		int width = view.getWidth();
		int height = view.getHeight();

		Bitmap b = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
		view.draw(new Canvas(b));
		return b;
	}

	Timer mProTimer = null;
	int proValue = 0;
	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			VerticalProgressBar progeree = (VerticalProgressBar) findViewById(R.id.progress);
			progeree.setProgress(proValue);
		}
	};

	void setProgeress(final int index) {
		if(mArray == null || mArray.size() == 0) return;
		
		final View view = lists.get(index);
		final JSONObject item = mArray.getJSONObject(index);
		String time = item.getString("time");
		if (time.length() < 5)
			time = "0" + time;
		String now = Utils.ConverToString(new Date(), "HH:mm");

		if (item.getString("isFeeding").equals("true")) {
			((MilkWave) view.findViewById(R.id.wave_view)).setProgress(
					150, mContext.getString(R.string.feeding), "");
		} else if (time.compareTo(now) < 0) {
			int milk = item.getIntValue("consumed_ml");
			if (milk == 0) {
				((MilkWave) view.findViewById(R.id.wave_view)).setProgress(0,"", "");
			} else {
				int temp = item.getIntValue("prepared_temp");
				if (((DemoApp) mContext.getApplicationContext()).glbUnit == 1) {
					temp = (int) (1.8 * temp) + 32;
					((MilkWave) view.findViewById(R.id.wave_view)).setProgress(
							milk, "" + item.getFloat("consumed_ml").intValue(), temp + "°F");
				} else
					((MilkWave) view.findViewById(R.id.wave_view)).setProgress(
							milk, "" + item.getFloat("consumed_ml").intValue(), temp + "°C");
			}
		}

		view.findViewById(R.id.wave_view).invalidate();

		double before_total_feed = item.getDoubleValue("before_total_feed");
		double total_goal = item.getDoubleValue("total_goal");
		if (((DemoApp) mContext.getApplicationContext()).glbUnit == 1) {
			before_total_feed = before_total_feed * 0.0325;
			total_goal = total_goal * 0.0325;

			((TextView) findViewById(R.id.total)).setText(String.format("%.2f",
					before_total_feed));
			((TextView) findViewById(R.id.total0)).setText(String.format(
					"%.2f", total_goal));
		} else {
			((TextView) findViewById(R.id.total)).setText(""
					+ item.getFloat("before_total_feed").intValue());
			((TextView) findViewById(R.id.total0)).setText(""
					+ item.getFloat("total_goal").intValue());
		}

		if(totalGoal == 0) return;
		
		mGoal = (200 * item.getIntValue("before_total_feed")) / totalGoal;
		if (mProTimer != null) {
			mProTimer.cancel();
			mProTimer = null;
		}

		mProTimer = new Timer();
		mProTimer.schedule(new TimerTask() {
			@Override
			public void run() {
				if (proValue >= 200)
					mGoal = 190;

				if (proValue > mGoal)
					proValue--;
				else if (proValue < mGoal)
					proValue++;
				else {
					mProTimer.cancel();
					mProTimer = null;
				}

				handler.sendEmptyMessage(0);
			}
		}, 0, 10);
	}

	private List<View> lists = new ArrayList<View>();
	private ViewPagerAdapter adapter;

	public class ViewPagerAdapter extends PagerAdapter {
		public ViewPagerAdapter() {
		}

		@Override
		public int getCount() { // 获得size
			return lists.size();
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

		@Override
		public void destroyItem(View view, int position, Object object) // 销毁Item
		{
			if(lists.size() == 0) return;
			((ViewPager) view).removeView(lists.get(position));
		}

		@Override
		public Object instantiateItem(View view, int position) // 实例化Item
		{
			if(lists.size() == 0) return null;
			((ViewPager) view).addView(lists.get(position), 0);
			return lists.get(position);
		}
	}
	
	void showDetail()
	{
		int index = ((ViewPager) findViewById(R.id.vp)).getCurrentItem();
		
		Intent intent = new Intent(mContext,ConsumeDetailActivity.class);
		intent.putExtra("info", JSON.toJSONString(mArray.getJSONObject(index)));
		mContext.startActivity(intent);
	}

	void initPageView() {
		if(mArray == null || mArray.size() == 0)
			return;
		
		lists.removeAll(lists);
		if(adapter != null) adapter.notifyDataSetChanged();
		adapter = null;
		{
			adapter = new ViewPagerAdapter();
			ViewPager viewPager = (ViewPager) findViewById(R.id.vp);
			viewPager.setAdapter(adapter);
			viewPager.setOnPageChangeListener(new OnPageChangeListener() {
				@Override
				public void onPageScrollStateChanged(int arg0) {
					
				}

				@Override
				public void onPageScrolled(int arg0, float arg1, int arg2) {

				}

				@Override
				public void onPageSelected(int arg0) {
					mSelected = arg0;
					mAdapter.notifyDataSetChanged();
					setProgeress(mSelected);
				}
			});
		}
	
		String now = Utils.ConverToString(new Date(), "HH:mm");
		int size = mArray.size();
		for (int i = 0; i < size; i++) {
			JSONObject item = mArray.getJSONObject(i);

			View view = ((MainPageActivity) mContext).getLayoutInflater().inflate(R.layout.item_bottle, null);
			lists.add(view);
			
			view.setOnClickListener(new OnClickListener(){
				@Override
				public void onClick(View arg0) {
					showDetail();
				}
			});

			String time = item.getString("time");
			if (time.length() < 5) time = "0" + time;

			if (item.getString("isFeeding").equals("true")) {
				view.findViewById(R.id.bottle3).setVisibility(View.VISIBLE);
				view.findViewById(R.id.bottle2).setVisibility(View.INVISIBLE);
				view.findViewById(R.id.layout_top).setVisibility(View.VISIBLE);

				view.findViewById(R.id.wave_view).setVisibility(View.VISIBLE);
				((MilkWave) view.findViewById(R.id.wave_view)).setProgress(150, mContext.getString(R.string.feeding), "");
			} else if (time.compareTo(now) < 0) {
				view.findViewById(R.id.wave_view).setVisibility(View.VISIBLE);
				view.findViewById(R.id.layout0).setVisibility(View.INVISIBLE);

				int milk = item.getIntValue("consumed_ml");
				if (milk == 0) {
					((MilkWave) view.findViewById(R.id.wave_view)).setProgress(0, "", "");
				} else {
					int temp = item.getIntValue("prepared_temp");
					if (((DemoApp) mContext.getApplicationContext()).glbUnit == 1) {
						temp = (int) (1.8 * temp) + 32;
						((MilkWave) view.findViewById(R.id.wave_view)).setProgress(
										milk,"" + item.getFloat("consumed_ml").intValue(), temp + "°F");
					}
					else
					{
						((MilkWave) view.findViewById(R.id.wave_view)).setProgress(
										milk,"" + item.getFloat("consumed_ml").intValue(), temp + "°C");
					}
				}
			} 
			else 
			{
				view.findViewById(R.id.layout0).setVisibility(View.VISIBLE);

				((TextView) view.findViewById(R.id.text0)).setText(item.getString("time"));
				((TextView) view.findViewById(R.id.text3)).setText("" + item.getFloat("howMilk").intValue());

				double goal_ml = item.getDoubleValue("goal_ml");
				int temp = item.getIntValue("prepared_temp");
				if (((DemoApp) mContext.getApplicationContext()).glbUnit == 1) {
					temp = (int) (1.8 * temp) + 32;
					((TextView) view.findViewById(R.id.text2)).setText(temp + "°F");
					goal_ml = goal_ml * 0.0352;
					((TextView) view.findViewById(R.id.text1)).setText(String.format("%.1f", goal_ml) + "oz");
				} 
				else 
				{
					((TextView) view.findViewById(R.id.text2)).setText(temp + "°C");
					((TextView) view.findViewById(R.id.text1)).setText(item.getFloat("goal_ml").intValue() + "ml");
				}

				view.findViewById(R.id.wave_view).setVisibility(View.INVISIBLE);
				((MilkWave) view.findViewById(R.id.wave_view)).setProgress(0,"", "");
			}
		}

		adapter.notifyDataSetChanged();
		new Handler().postDelayed(new Runnable(){
			@Override
			public void run() {
				setProgeress(mSelected);
			}
		}, 200);
	}

	int mGoal = 0;

	public void sendHttpRequest(boolean show) {

		MgqDataHandler loginHandler = new MgqDataHandler(mContext, show, false) {
			@Override
			public void onSuccess(String response) {
				mArray = JSON.parseArray(response);
				if (mArray != null) {
					int count = mArray.size();
					if (count <= 8)
						mScreenWidth = ((WindowManager) mContext
								.getSystemService(Context.WINDOW_SERVICE))
								.getDefaultDisplay().getWidth()
								/ count;
					else
						mScreenWidth = ((WindowManager) mContext
								.getSystemService(Context.WINDOW_SERVICE))
								.getDefaultDisplay().getWidth() / 8;

					if (mHeight == 0) {
						mHeight = findViewById(R.id.layout_top).getHeight();
					}

					mAdapter.notifyDataSetChanged();

					if (mArray.size() > 0) {
						initPageView();
						
						totalGoal = mArray.getJSONObject(mArray.size() - 1)
								.getIntValue("total_goal");
						if (((DemoApp) mContext.getApplicationContext()).glbUnit == 1) {
							double temp = totalGoal * 0.0325;

							((TextView) findViewById(R.id.goal)).setText(String
									.format("%.2f", temp));
						} else {
							((TextView) findViewById(R.id.goal)).setText(""
									+ totalGoal);
						}

						if (mSelected == -1 || mSelected >= mArray.size())
							mSelected = 0;

						if (MainNoticeActivity.mTime != null) {
							for (int i = 0; i < count; i++) {
								JSONObject item = mArray.getJSONObject(i);

								String time = item.getString("time");
								if (time.equals(MainNoticeActivity.mTime)) {
									MainNoticeActivity.mTime = null;
									mSelected = i;
									((ViewPager) findViewById(R.id.vp)).setCurrentItem(mSelected);
									break;
								}
							}
						} else {
							for (int i = 0; i < count; i++) {
								JSONObject item = mArray.getJSONObject(i);

								String time = item.getString("isSelect");
								if (time.equals("true")) {
									mSelected = i;
									((ViewPager) findViewById(R.id.vp)).setCurrentItem(mSelected);
									break;
								}
							}
						}
					}
				}
				// sendChartHttpRequest();
			}
		};

		JSONObject params = new JSONObject();
		params.put("mia_un", PreferencesUtils.getString(mContext, "username"));
		params.put("pwd", PreferencesUtils.getString(mContext, "password"));

		MgqRestClient.postBody(Constant.SERVER_URL
				+ "/sw/DashboardHeadApi.ashx", JSON.toJSONString(params),
				loginHandler);
	}

	/*
	 * private void sendChartHttpRequest() { MgqDataHandler loginHandler = new
	 * MgqDataHandler(mContext, false, false) {
	 * 
	 * @SuppressWarnings("unchecked")
	 * 
	 * @Override public void onSuccess(String response) { JSONArray array =
	 * JSON.parseArray(response);
	 * 
	 * JSONArray mJsonArray = new JSONArray(); for(int i = 6; i >= 0; i--) {
	 * mJsonArray.add(array.getJSONObject(i)); }
	 * 
	 * int width = ((WindowManager)
	 * mContext.getSystemService(Context.WINDOW_SERVICE
	 * )).getDefaultDisplay().getWidth()/7; int height =
	 * findViewById(R.id.bottom).getHeight();
	 * 
	 * for(int j = 0; j < 7; j++) { DrinkView lineView =
	 * (DrinkView)findViewById(R.id.line0 + j);
	 * lineView.setPoint(mJsonArray,height,width,600,j); } } };
	 * 
	 * Date date = new Date(System.currentTimeMillis()); Date date0 = new
	 * Date(System.currentTimeMillis() - 6*24*3600*1000);
	 * 
	 * String end = Utils.ConverToString(date, "yyyy-MM-dd"); String start =
	 * Utils.ConverToString(date0, "yyyy-MM-dd");
	 * 
	 * JSONObject params = new JSONObject(); params.put("mia_un",
	 * PreferencesUtils.getString(mContext, "username")); params.put("pwd",
	 * PreferencesUtils.getString(mContext, "password"));
	 * params.put("start_date", start); params.put("end_date", end);
	 * 
	 * Calendar cal = Calendar.getInstance(); cal.setTime(date0); int w =
	 * cal.get(Calendar.DAY_OF_WEEK) - 1; for(int i = R.id.week0; i <=
	 * R.id.week6; i++) { int week = w + (i - R.id.week0); if(week >= 7) week -=
	 * 7;
	 * 
	 * ((TextView)findViewById(i)).setText(Utils.dayOfWeek(mContext,week)); }
	 * 
	 * MgqRestClient.postBody(Constant.SERVER_URL +
	 * "/sw/GetHistoryFeedData.ashx", JSON.toJSONString(params), loginHandler);
	 * }
	 */
	class HorizontalListViewAdapter extends BaseAdapter {
		private LayoutInflater mInflater;

		public HorizontalListViewAdapter(Context con) {
			mInflater = LayoutInflater.from(con);
		}

		@Override
		public int getCount() {
			if (mArray != null)
				return mArray.size();
			return 0;
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		private class ViewHolder {
			private TextView time;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder vh = null;

			if (convertView == null) {
				vh = new ViewHolder();
				convertView = mInflater.inflate(R.layout.item_time, null);
				vh.time = (TextView) convertView.findViewById(R.id.time);
				convertView.setTag(vh);
			} else {
				vh = (ViewHolder) convertView.getTag();
			}

			vh.time.setText(mArray.getJSONObject(position).getString("time"));
			android.view.ViewGroup.LayoutParams params = vh.time
					.getLayoutParams();
			params.width = mScreenWidth;
			vh.time.setLayoutParams(params);

			if (position != mSelected) {
				convertView.setBackgroundColor(Color.rgb(15,192,219));
			} else {
				convertView.setBackgroundColor(Color.rgb(13,128,214));
			}

			
			String now = Utils.ConverToString(new Date(), "HH:mm");
			String time = mArray.getJSONObject(position).getString("time");
			String isWater = mArray.getJSONObject(position).getString("isWater");
			
			if (time.length() < 5) time = "0" + time;
			if (time.compareTo(now) < 0)
			{
				vh.time.setTextColor(Color.WHITE);
			}
			else
			{
				vh.time.setTextColor(Color.rgb(167,222,231));
			}
					
			vh.time.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
			if(isWater.equals("true"))
			{
				vh.time.setCompoundDrawablesWithIntrinsicBounds(R.drawable.water, 0, 0, 0);
			}
			
			convertView.setOnTouchListener(DashboardActivity.this);
			return convertView;
		}
	}

	public void changeTime(boolean isAdd) {
		if (mArray == null || mArray.size() == 0)
			return;

		if (isAdd) {
			if (mSelected > 0) {
				mSelected--;
				mAdapter.notifyDataSetChanged();
				setProgeress(mSelected);
			}
		} else {
			if (mSelected < mArray.size() - 1) {
				mSelected++;
				mAdapter.notifyDataSetChanged();
				setProgeress(mSelected);
			}
		}
	}
}
